<template>
  <div class="page white-stage">
    <div class="team-main">
      <group class="no-margin">
        <x-input title="团队名称" v-model="team.team_name" placeholder="请输入团队名称" novalidate :icon-type="iconType" :show-clear="false" @on-blur="onBlur" placeholder-align="right"></x-input>
        <cell @click.native ="selectManager" direction="rtl" title="营销主管" :value="selectManagerValue"  ></cell>
        <cell @click.native="selectMembers" direction="rtl" title="营销顾问" :value="selectMembersValue" ></cell>
      </group>
      <div class="btn-group">
        <span class="btn save-btn" @click="saveTeam">保存</span>
      </div>
      </div>
    </div>
</template>

<script>
  import Vue from 'vue'
  import clientMenu from '../components/client-menu'
  import {XInput, Group, Selector, Cell} from 'vux'
  import store from '../store'

  export default{
    data() {
      return {
        teamId: '',
        team:{},
        iconType: '',
        teamname: '天润校营销团队',

        team_managers: [],
        team_members: [],
        selected_team_managers:[],
        selected_team_members:[],
        selectManagerValue: '选择营销主管',
        selectMembersValue: '请选择营销顾问',

        mkChargerValue: '0',
        counselorValue: '0',

        // clientSourceValue: '',
        // industryValue: '',
        // teamGenderValue: '',

        marketingChargers: [
        {
          key : '0',
          value: '李丽萍'
        },
        {
          key: '1',
          value: '林宇'
        }
        ],

        counselor : [

        {
          key: '0',
          value:'林丽亲'
        },

        {
          key:'1',
          value:'李美英'}
        ],

        amounts : [

        {
          key: '0',
          value:'100'
        },

        {
          key:'1',
          value:'50'
        }
        ]
      }
    },
    components:{
      XInput,
      Group,
      Selector,
      Cell
    },
    methods: {
      refresh (iscroll) {
      console.log('refresh')
      // Refresh current data
      },

      log () {
      console.log('ee');
      },

      load (iscroll) {
      console.log('load')
      // Load new data
      },

      test () {
      console.log('test')
      },

      onBlur () {

      },

      onShow () {
      console.log(arguments)
      },

      saveTeam() {
        let that = this;

        store.dispatch('saveTeams', that.team)
        .then(function(response){
          if(response.data.errcode === 0) {
          alert('保存成功!');
          that.$router.back();
          } else {
          console.debug('系统出错!请联系管理员', response.data);
          }
        }).catch((error) =>{
          console.debug(error, '系统出错!请联系管理员')
        });
        console.log("this.team", JSON.stringify(that.team), that.team.id);

        // let response = {errcode:0};
        //
        // if(response.errcode === 0) {
        //   alert('保存成功!');
        //   this.$router.back();
        // } else {
        //   alert('系统出错!请联系管理员');
        // }
      },


      // 编辑初始化选择的主管、成员
      initTeamInfo(id) {
        let that = this;

        store.dispatch('getTeam', id)
        .then(function(response) {

          if(response.data.errcode === 0) {
          let team_managers = [];
          let selected_team_managers = [];
          let selected_team_members = [];

          that.team = response.data.results;
          that.team.team_managers
            .forEach(function(element){
            // console.log('element.ding_user_id', element, elemnt.suid, element.ding_user_id)
            selected_team_managers.push({
              emplId: element.ding_user_id || element.suid,
              name : element.name
            })
            });

          that.selected_team_managers = selected_team_managers;
          that.team_managers = that.team.team_managers

          that.team.team_members
            .forEach(function(element){
            // console.log('element.ding_user_id', element, elemnt.suid, element.ding_user_id)
            selected_team_members.push({
              emplId: element.ding_user_id || element.suid,
              name : element.name
            })
            });

          that.selected_team_members = selected_team_members;
          that.team_members = that.team.team_members
          that.team.id = id;
          console.log(JSON.stringify(that.selected_team_members))

          } else {
          console.debug('系统出错!请联系管理员', response.data);
          }
        }).catch((error) => {
          console.log(error)
        });

        // let response = {
        //   "errcode": 0,
        //   "errmsg": "获取团队详情成功",
        //   "results": {
        //   	"parent_id": "0",
        //   	"team_name": "爬起来",
        //   	"team_managers": [{
        //   		"ding_user_id": "007",
        //   		"name": "王雪兵"
        //   	}, {
        //   		"ding_user_id": "0131681309240",
        //   		"name": "周斌"
        //   	}, {
        //   		"ding_user_id": "055917325037670572",
        //   		"name": "陈千镇"
        //   	}, {
        //   		"ding_user_id": "02582046003125406",
        //   		"name": "甄健雄"
        //   	}],
        //   	"team_members": [{
        //   		"ding_user_id": "50424662689427",
        //   		"name": "吴勇"
        //   	}, {
        //   		"ding_user_id": "0625183017842894",
        //   		"name": "李娜"
        //   	}, {
        //   		"ding_user_id": "008",
        //   		"name": "任洁卿-财务"
        //   	}]
        //   }
        // };

        // if(response.errcode === 0) {
        //   let team_managers = [];
        //   let selected_team_managers = [];
        //   let selected_team_members = [];
        //
        //   that.team = response.results;
        //   that.team.team_managers
        //   .forEach(function(element){
        //     selected_team_managers.push({
        //     emplId: element.ding_user_id,
        //     name : element.name
        //     })
        //   });
        //
        //   that.selected_team_managers = selected_team_managers;
        //   that.team_managers = that.team.team_managers
        //
        //   that.team.team_members
        //   .forEach(function(element){
        //     selected_team_members.push({
        //     emplId: element.ding_user_id,
        //     name : element.name
        //     })
        //   });
        //
        //   that.selected_team_members = selected_team_members;
        //   that.team_members = that.team.team_members
        //   that.team.id = this.teamId;
        //
        // } else {
        //   alert('系统出错!请联系管理员');
        // }
      },


      selectManager () {

        console.log('selectManager')
        var that = this;
        let users = [];

        this.selected_team_managers
        .forEach(function(element){
          users.push(element.emplId);
        })


        this.callJsApi('biz.contact.choose',{users: users})
        .then(function(data){
          console.log(JSON.stringify(data));

          var team_managers = [];

          data.forEach(function(object, index){
            team_managers.push({
              ding_user_id : object.emplId,
              name : object.name
            })
          });

          that.team_managers = team_managers;
          that.team.team_managers = team_managers;
          that.selected_team_managers = data;
        });
      },

      selectMembers () {

      var that = this;
      let users = [];

      this.selected_team_members.forEach(function(element){
        users.push(element.emplId);
      })
      console.log('users: ', JSON.stringify(users))

      this.callJsApi('biz.contact.choose',{
        users: users,
      }).then(function(data){

        var team_members = [];

        data.forEach(function(object, index) {
          team_members.push({
            ding_user_id : object.emplId,
            name : object.name
          })
        });

        console.log(that, 'team_members');

        that.team_members = team_members;
        that.team.team_members = team_members;
        that.selected_team_members = data;
      });
      }

    },

    watch:{

      mkChargerValue(value){
        this.team.orderway = value;
      },
      counselorValue(value){
        this.team.counselor = value;
      },
      amountValue(value){
        this.team.amount = value;
      },

      team_members(value) {

        var selectManagerValue = '';
        var isNotElippse = false;

        this.selected_team_members.forEach(function(object, index){
          if(index < 3) {
            selectManagerValue += (index === 0 ? '' : '、')+object.name;
          } else if(isNotElippse === false) {
            selectManagerValue += '...';
            isNotElippse = true;
          }
        });

        this.selectMembersValue = selectManagerValue;
      },

      team_managers(value) {


        var selectManagerValue = '';
        var isNotElippse = false;

        this.selected_team_managers.forEach(function(object, index){
          if(index < 3) {
            selectManagerValue += (index === 0 ? '' : '、')+object.name;
          } else if(isNotElippse === false) {
            selectManagerValue += '...';
            isNotElippse = true;
          }
        });

        this.selectManagerValue = selectManagerValue;
      }

    },

    mounted () {

      this.callJsApi('biz.navigation.setTitle',{title:'编辑团队'});

      this.teamId = this.$route.query.id;


      this.initTeamInfo(this.teamId);

      console.log('edit-team', JSON.stringify(this.team), this.team.id);

    }


  }
</script>

<style lang='less'>
  @import "../less/index.less";

  .team-main{

  .no-margin{
     &>*{
     margin: 0
     }
  }

  .add-new-btn{
    width: 60%;
  }

  .btn-group{
    margin-top: 15px;

    &>*{
    width: 80%;
    text-align: center;
    border-radius: 4px;
    padding: 10px;
    margin: 0 auto;
    border: 1px solid rgb(229, 229, 229);
    background-color: white;
    color:#23B2E2;
    display: block;
    }

    .pull-left{
    float: left;
    }

    .pull-right{
    float: right;
    }
  }

  }
</style>
